#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        unordered_map<int, int> mp;
        int n1 = inorder.size();
        int n2 = postorder.size();

        for (int i = 0; i < n1; i++) {
            mp[inorder[i]] = i;
        }

        function<TreeNode* (int, int, int, int)> fa = [&](int pl, int pr, int il, int ir)-> TreeNode* {
            if (pl > pr || il > ir)return nullptr;
            int val = postorder[pr];
            int ipos = mp[val];
            TreeNode* newroot = new TreeNode(val);

            int lnum = ipos - il;
            newroot->left = fa(pl, pl + lnum - 1, il, ipos - 1);
            newroot->right = fa(pl + lnum, pr - 1, ipos + 1, ir);
            return newroot;
            };

        return fa(0, n2 - 1, 0, n1 - 1);
    }
};